package com.wdl.modules.myhouse.utils.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.wdl.modules.myhouse.security.common.SecurityConstant;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

public class JWTUtils {
    private static String SIGNATURE = SecurityConstant.TOKEN_SIGN;

    /**
     * 生成token
     *
     * @param map //传入payload
     * @return 返回token
     */
    public static String createToken(Map<String, String> map, Date expiredTime) {
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });
        if (expiredTime != null) {
            builder.withExpiresAt(expiredTime);
        }
        return builder.sign(Algorithm.HMAC256(SIGNATURE));
    }

    /**
     * 验证token
     *
     * @param token
     */
    public static void verify(String token) {
        JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }

    /**
     * 获取token中payload
     *
     * @param token
     * @return
     */
    public static DecodedJWT getToken(String token) throws JWTDecodeException {
        return JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }
}
